package cn.valorin.event;

import static cn.valorin.configuration.languagefile.MessageSender.sm;

import java.util.List;

import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import cn.valorin.Main;
import cn.valorin.item.RawZongzi;
import cn.valorin.item.Zongzi;
import cn.valorin.util.CheckLore;
import cn.valorin.util.EatingCommands;
import cn.valorin.util.EatingTell;

public class EatEvent implements Listener {
	@SuppressWarnings("deprecation")
	@EventHandler
	public void eat(PlayerInteractEvent e) {
		Player player = e.getPlayer();
		if (!e.getAction().equals(Action.RIGHT_CLICK_AIR) && !e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
			return;
		}
		ItemStack item = e.getItem();
		if (item == null) { return; }
		if (CheckLore.check(item, Zongzi.get(player))) {
			FileConfiguration config = Main.getInstance().getConfig();
			if (player.getItemInHand().getAmount() == 1) {
				player.setItemInHand(new ItemStack(Material.AIR));
			} else {
				ItemStack temp = player.getItemInHand();
				temp.setAmount(temp.getAmount() - 1);
				player.setItemInHand(temp);
			}
			  
			  double health = player.getHealth();
			  int food = player.getFoodLevel();
			  double health_add = config.getDouble("Zongzi.Health");
			  int food_add = config.getInt("Zongzi.Food");
			  
			  if (player.getMaxHealth() - health < health_add) {
				  player.setHealth(player.getMaxHealth());
			  } else {
				  player.setHealth(health + health_add);
			  }
			  
			  if (20 - food < food_add) {
				  player.setFoodLevel(20);
			  } else {
				  player.setFoodLevel(food + food_add);
			  }
			  
		      List<String> executeList = config.getStringList("Zongzi.Action");
		      if (executeList.size() != 0) {
		    	  for (String str : executeList) {
		    	      if (str.startsWith("tell:")) {
		    		      EatingTell.tellMessage(player, str);
		    	      }
		    	      if (str.startsWith("command:")) {
		    	          EatingCommands.ExecuteCommands(player, str);
		    	      }
		    	  }
		      }
		}
	}
	
	@EventHandler
	public void eat(PlayerItemConsumeEvent e) {
		Player player = e.getPlayer();
		ItemStack item = e.getItem();
		if (item.isSimilar(RawZongzi.get(player))) {
			new PotionEffect(PotionEffectType.SLOW,20,2).apply(player);
			new PotionEffect(PotionEffectType.BLINDNESS,20,1).apply(player);
			sm("&c你吃了生粽子，感到身体不适。请将粽子煮熟后再食用",player);
		}
	}
}
